#!/usr/bin/env python

# An example for a daemon process to loop endlessly taking as much data
# from a currentcost device as it can and storing that data in an rrd
# and/or a plain text file.
# pir 2010/03/18

# Global variables
BASE = '/usr/local/power'    # A directory to store everything underneath.
PORT = '/dev/cu.usbserial'   # The port connected to the currentcost.
BAUD = 9600                  # 9600 for a classic, 57600 for a cc128.
RRD = '%s/rrd/cc.rrd' % BASE # rrdtool file, this need to be created first.
LOG = '%s/var/output.txt' % BASE # Plain text output file.
DEBUG = False
#DEBUG = True

import sys
# Where to find pycurrentcost.py
sys.path.append('%s/lib' % BASE)
import pycurrentcost

import os
import rrdtool
import syslog
import tempfile
import time

syslog.openlog(os.path.basename(sys.argv[0]),
               (syslog.LOG_PID|syslog.LOG_CONS|syslog.LOG_PERROR),
               syslog.LOG_DAEMON)
if DEBUG:
  syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG))
else:
  syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_ERR))

# Init the CurrentCost unit.
cc = pycurrentcost.CurrentCostReader(port=PORT, baudrate=BAUD)

# Open the plain text logfile.
logfile = open(LOG, 'a')

# Loop and take readings.
while True:

  try:
    reading = cc.get_reading()
  except pycurrentcost.CurrentCostException, e:
    syslog.syslog(syslog.LOG_ERR, 'Error from get_reading: %s' % e)

  else:
    updatestr = str(u'%d:%s:%s' % (int(time.time()),
                                   reading.channels[1]['watts'],
                                   reading.temperature))
    syslog.syslog(syslog.LOG_DEBUG,
                  'Got data: %s %s' % (RRD, updatestr))

    # Write to a flat text file.
    logfile.write('%s\n' % updatestr)
    logfile.flush()

    # Write to an rrd.
    try:
      rrdtool.update(RRD, updatestr)
    except rrdtool.error, e:
      syslog.syslog(syslog.LOG_ERR, 'Error updating RRD: %s' % e)
   
